package com.example.sicnuaccountingapp.ui.home

import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Toast
import androidx.fragment.app.Fragment
import androidx.fragment.app.viewModels
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.lifecycleScope
import androidx.lifecycle.repeatOnLifecycle
import androidx.recyclerview.widget.LinearLayoutManager
import com.example.sicnuaccountingapp.databinding.FragmentHomeBinding
import com.example.sicnuaccountingapp.data.entity.Transaction
import com.example.sicnuaccountingapp.ui.transaction.AddTransactionDialog
import com.example.sicnuaccountingapp.ui.transaction.EditTransactionDialog
import com.example.sicnuaccountingapp.utils.PreferencesManager
import dagger.hilt.android.AndroidEntryPoint
import kotlinx.coroutines.launch
import javax.inject.Inject

@AndroidEntryPoint
class HomeFragment : Fragment() {
    private var _binding: FragmentHomeBinding? = null
    private val binding get() = _binding!!

    private val viewModel: HomeViewModel by viewModels()
    private lateinit var transactionAdapter: GroupedTransactionAdapter

    @Inject
    lateinit var preferencesManager: PreferencesManager

    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View {
        _binding = FragmentHomeBinding.inflate(inflater, container, false)
        return binding.root
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        setupViews()
        observeState()
        
        viewModel.setUserId(preferencesManager.userId)
    }

    private fun setupViews() {
        setupRecyclerView()
        
        binding.addTransactionFab.setOnClickListener {
            showAddTransactionDialog()
        }
    }

    private fun setupRecyclerView() {
        transactionAdapter = GroupedTransactionAdapter(
            onItemClick = { transaction ->
                showEditTransactionDialog(transaction)
            }
        )
        
        binding.transactionList.apply {
            adapter = transactionAdapter
            layoutManager = LinearLayoutManager(context)
        }
    }

    private fun observeState() {
        viewLifecycleOwner.lifecycleScope.launch {
            viewLifecycleOwner.repeatOnLifecycle(Lifecycle.State.STARTED) {
                viewModel.state.collect { state ->
                    when (state) {
                        is HomeUiState.Success -> {
                            updateSummary(state.summary)
                            transactionAdapter.submitList(state.transactions.toList())
                        }
                        is HomeUiState.Error -> {
                            Toast.makeText(context, state.message, Toast.LENGTH_SHORT).show()
                        }
                        HomeUiState.Loading -> {
                            // 可以显示加载状态
                        }
                    }
                }
            }
        }
    }

    private fun updateSummary(summary: TransactionSummary) {
        binding.apply {
            incomeAmount.text = String.format("¥%.2f", summary.totalIncome)
            expenseAmount.text = String.format("¥%.2f", summary.totalExpense)
        }
    }

    private fun showAddTransactionDialog() {
        EditTransactionDialog.newInstance()
            .show(childFragmentManager, EditTransactionDialog.TAG)
    }

    private fun showEditTransactionDialog(transaction: Transaction) {
        EditTransactionDialog.newInstance(transaction)
            .show(childFragmentManager, EditTransactionDialog.TAG)
    }

    override fun onDestroyView() {
        super.onDestroyView()
        _binding = null
    }
} 